use serde_json;
use std::default::Default;

#[derive(Serialize, Deserialize)]
pub struct Config {
    pub post_path: String,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            post_path: "127.0.0.1:5700".to_string(),
        }
    }
}

impl Config {
    pub fn from_file(path: &str) -> Config {
        use std::fs::OpenOptions;
        use std::io::Read;

        let mut opt = OpenOptions::new();
        opt.create(true).write(true).read(true).append(false);

        if let Ok(mut file) = opt.open(path) {
            let mut data = String::new();
            if let Ok(_) = file.read_to_string(&mut data) {
                if let Ok(rt) = serde_json::from_str(&data) {
                    return rt;
                } else {
                    error!("fail to deserialize config file from path '{}'", path)
                }
            }
        } else {
            error!("fail to open config file from '{}'", path);
        }
        return Config::default();
    }

    pub fn save_to_file(&self, path: &str) {
        use std::fs::OpenOptions;
        use std::io::Write;

        let mut opt = OpenOptions::new();
        opt.create(true).write(true).read(true).append(false);

        match opt.open(path) {
            Err(e) => {
                error!("fail to open {}, {:?}", path, e);
            }
            Ok(mut file) => {
                let json_str = serde_json::to_string_pretty(&self).unwrap();
                file.write(json_str.as_bytes()).unwrap();
                file.sync_all().unwrap();
            }
        }
    }
}